const puppeteer = require('puppeteer');

const userAgents = [
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36',
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36',
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36',
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304.110 Safari/537.36',
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304.87 Safari/537.36',
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
  'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304.36 Safari/537.36',
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5410.0 Safari/537.36'
  // ... 添加更多的 User-Agent
];

let globalBrowserPromise = null;

async function launchBrowser() {
  try {
    const browser = await puppeteer.launch({
      // headless: false,
      headless: true,// 启用无头模式
      // ignoreHTTPSErrors: true, // 忽略 HTTPS 错误
      args: [
        '--disable-logging', // 禁用日志
        '--log-level=3', // 设置日志级别为错误
        '--disable-gpu', // 禁用 GPU 加速
        '--no-sandbox', // 禁用沙盒
        '--disable-setuid-sandbox', // 禁用 setuid 沙盒
        '--disable-dev-shm-usage', // 禁用 /dev/shm 使用
        '--no-first-run', // 禁用首次运行
        '--no-zygote', // 禁用 Zygote 进程
        '--disable-features=Permissions-Policy', // 禁用 Permissions-Policy
        '--disable-notifications', // 禁用通知
        '--enable-automation', // 启用自动化
        '--disable-features=SameSiteByDefaultCookies', // 禁用 SameSite 默认 Cookie
      ],
      dumpio: false, // 不输出 IO 日志
    });
    console.log('启动全局浏览器');
    return browser;
  } catch (err) {
    console.error('浏览器出错~~~！！！！！！！:', err);
    throw err;
  }
}

async function getRandomUserAgent() {
  const randomIndex = Math.floor(Math.random() * userAgents.length);
  return userAgents[randomIndex];
}

async function getRandomReferer(refererList) {
  const randomIndex = Math.floor(Math.random() * refererList.length);
  return refererList[randomIndex];
}

async function createPage() {
  if (!globalBrowserPromise) {
    globalBrowserPromise = launchBrowser();
  }

  console.log('启动全局浏览器--新建页面');
  const globalBrowser = await globalBrowserPromise;

  const page = await globalBrowser.newPage();
  const randomUserAgent = await getRandomUserAgent();
  // console.log(randomUserAgent);
  await page.setUserAgent(randomUserAgent);

  const randomWidth = Math.floor(Math.random() * (1920 - 800)) + 800;
  const randomHeight = Math.floor(Math.random() * (1080 - 600)) + 600;

  await page.setViewport({
    width: randomWidth,
    height: randomHeight,
  });

  await page.setExtraHTTPHeaders({
    'Accept-Language': 'zh-CN'
  });

  await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false,
    });
  });

  const refererList = [
    'https://www.google.com',
    'https://www.baidu.com',
    'https://www.zaidu.in',
    // 添加更多Referer
  ];

  const randomReferer = await getRandomReferer(refererList);
  // console.log(randomReferer);

  await page.setRequestInterception(true);

  page.on('request', async (request) => {
    // 获取请求资源的类型
    const resourceType = request.resourceType();

    // 如果是图片或样式表，则阻止请求
    if (resourceType === 'image' || resourceType === 'stylesheet') {
      request.abort();
    } else {
      // 只有当请求不是图片或样式表时，才继续请求并修改请求头
      request.continue({
        headers: {
          ...request.headers(),
          referer: randomReferer, // 确保 randomReferer 变量已定义并有效
        },
      });
    }
  });


  const pages = await globalBrowser.pages();
  console.log('当前浏览器标签页数量：' + pages.length);
  if (pages.length > 5) {
    for (let i = 3; i < pages.length - 1; i++) {
      await pages[i].close();
    }
  }

  return { globalBrowser, page };
}

module.exports = createPage;
